import { _decorator, Button, Component, instantiate, isValid, Layout, log, Node, Prefab } from 'cc';

import { RoomPlayer } from './components/player/RoomPlayer';

import { RoomStore } from '../store/Room@Store';
import { EDITOR } from 'cc/env';
import { CreateRoomWebSocket } from '../ws/Room@WebSocket';
import { cat, RoomStatus, SceneLayer } from '../Test';


const { ccclass, property } = _decorator;

type SceneMatchProps = {
    is_ready: boolean
}

if (!EDITOR) {
    console.time('[Room WS Init]');
    CreateRoomWebSocket()
    console.timeEnd('[Room WS Init]')

    // 项目APP初始化之后的处理APP初始化事务
    console.time('[Room Store Init]');
    cat.merge('store', { room: new RoomStore(cat.store) })
    console.timeEnd('[Room Store Init]')
}


cat?.socialGameClient?.onEventHideDelegate.add(() => {
    // 如果在游戏中 就不让退出了
    if (![RoomStatus.STARTED].includes(cat.store.room.roomInfo.status)) {
        LeaveRoom()
        log('SET_EVENT_HIDE_BEFORE_CB', cat.store.room.roomInfo.status)
    }
})


@ccclass('SceneRoom')
export class SceneRoom extends SceneLayer {

    @property({ type: Button, tooltip: '取消按钮' })
    btn_cancel_match: Button

    @property({ type: Node, tooltip: '匹配loading' })
    ui_match_loading: Node

    @property({ type: Prefab, tooltip: '匹配玩家预制体' })
    match_player_prefab: Prefab

    @property({ type: Layout, tooltip: '玩家座位列表节点' })
    player_list: Layout

    @property({ type: Prefab, tooltip: '游戏倒计时预制体' })
    game_timeout_prefab: Prefab

    /**倒计时UI */
    private game_timeout_ui: Node | null = null

    /**座位 */
    private seats: RoomPlayer[] = [];

    override props: SceneMatchProps = {
        is_ready: false
    }


    protected override initUI(): void {


    }

    protected override async onLoad(): Promise<void> {

        await QueryAliveRoom()

        if (cat.store.room.roomInfo.status === RoomStatus.STARTED) {
            if (!cat.store.room.roomInfo.battleInfo?.id) {
                cat.gui.showLoading({ title: '请刷新网页,重新加入游戏中' })
                window.location.reload()
            }
        } else {
            console.log(this.props.is_ready, cat.store.room.roomInfo.id)
            if (this.props.is_ready && cat.store.room.roomInfo.id) {
                await cat.room_ws.RoomReady(cat.store.room.roomInfo.id)
            }

        }

    }

    protected override start(): void {

    }

    override onDestroy(): void {
        this.unscheduleAllCallbacks()
    }



    protected override onAutoObserver(): void {
        this.addAutorun([
            () => {
                const { seats } = cat.store.room.roomInfo
                log('seats', seats)
                if (seats.length) {
                    if (!this.seats.length) {
                        const nonce: RoomPlayer[] = [];
                        seats.forEach(item => {
                            const node = instantiate(this.match_player_prefab)
                            const player = node.getComponent(RoomPlayer)!.addToParent(this.player_list, { props: item })
                            nonce.push(player)
                        })
                        this.seats = nonce
                    } else {
                        seats.forEach((item, index) => {
                            const seat = this.seats[index]
                            seat.setOptions({
                                props: item
                            })
                        })
                    }
                }
            }
        ])
        this.addReaction(
            () => (cat.store.room.roomInfo.status === RoomStatus.STARTED) && cat.store.room.roomInfo.battleInfo?.id && cat.store.game.game_token,
            (condition) => {
                log('获取游戏数据中', cat.store.room.roomInfo.status, RoomStatus.STARTED, cat.store.room.roomInfo.battleInfo?.id)
                if (condition) { //开始并创建了战局
                    cat.gui.showLoading({ title: '获取游戏数据中' })
                    const { id = '', serverId = '' } = cat.store.room.roomInfo?.battleInfo ?? {}
                    log('================================', id, serverId)
                    CreateGameWebSocket().connectRequest({
                        battle_id: id,
                        serverId,
                        token: cat.store.game.game_token
                    }).then(() => {
                        cat.gui.loadScene('game');
                    })
                }
            },
            { fireImmediately: true }
        )
    }


}


